package bsc.war.handler;

import bsc.ejb.entity.DimensionalCut;
import bsc.ejb.entity.Pointer;
import bsc.ejb.entity.ScoreCard;
import bsc.ejb.metadata.Colorimetry;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.model.Score;
import bsc.war.service.ScoreCardUtils;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author Memo
 */
public class DrillScoreCard extends AbstractController {

    public DrillScoreCard() {
    }

    @Override
    protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");
            processRequestInternal(request, response, delegate);

        } catch (Exception e) {
            logger.error("Catched exception", e);
        }
        return new ModelAndView("drillScoreCard");
    }

    public static void processRequestInternal(HttpServletRequest request,
            HttpServletResponse response, DelegateBSC delegate) {


        if (request.getParameter("scoreCard") != null && request.getParameter("scoreCard").length() > 0) {
            Long idScoreCard = Long.parseLong(request.getParameter("scoreCard"));
            ScoreCard scoreCardFather = delegate.findScoreCard(idScoreCard);

            // ScoreCard scoreCard = delegate.findScoreCard(idScoreCard);
            // Comparation comparation = delegate.findComparation(2L);

            //System.out.println("Nombre del ScoreCard: " + scoreCard.getName());
            List<ScoreCard> scoreCardsRoot = delegate.findOtherScoreCards(idScoreCard);
            Map<ScoreCard, String> scoreCardColor = new HashMap<ScoreCard, String>();
            Map<ScoreCard, Double> scoreCardScore = new HashMap<ScoreCard, Double>();
            Map<ScoreCard, Integer> scoreCardChildren = new HashMap<ScoreCard, Integer>();
            Map<ScoreCard, Double> scoreCardChildrenWeight = new HashMap<ScoreCard, Double>();
            for (ScoreCard scoreCard : scoreCardsRoot) {
                Score score = ScoreCardUtils.calculateScore(delegate, ScoreCardUtils.getSystemComparation(request), scoreCard, ScoreCardUtils.getSystemDate(request));
                Double weight = ScoreCardUtils.getPercentFactor(delegate, scoreCardFather, scoreCard);
                /*
                System.out.println("Comparation: " + ScoreCardUtils.getSystemComparation(request));
                System.out.println("Pointer: " + scoreCard.getName());
                System.out.println("Date: " +ScoreCardUtils.getSystemDate(request).toString());
                 */
                //PONDERACION
                scoreCardChildrenWeight.put(scoreCard, weight);
                if(scoreCard instanceof Pointer){
                    if(!score.isOutOfDate()) {
                        scoreCardScore.put(scoreCard, score.getScore());
                        Colorimetry colorimetry = delegate.findColorimetry(scoreCard, score.getScore());
                        scoreCardColor.put(scoreCard, colorimetry == null ? "" : colorimetry.getColor() + "");
                    }
                }else{
                    scoreCardScore.put(scoreCard, score.getScore());
                    Colorimetry colorimetry = delegate.findColorimetry(scoreCard, score.getScore());
                    scoreCardColor.put(scoreCard, colorimetry == null ? "" : colorimetry.getColor() + "");
                }
                //scoreCardScore.put(scoreCard1, new Double(0));
                scoreCardChildren.put(scoreCard, new Integer(delegate.findScoreCard(scoreCard).size()));
            }


            //Update members of all dimensional cuts
            //List of all DimensionalCuts
            List<DimensionalCut> dimensionalCuts = ScoreCardUtils.getDimensionalCuts(request, delegate);

            //Se obtiene los strings de los cuts
            java.util.Map<DimensionalCut, String> dimensionalCutsMembers = ScoreCardUtils.getDimensionalCutsMembersStrings(request, delegate, dimensionalCuts);

            request.setAttribute("parentScorecard", idScoreCard);
            request.setAttribute("scoreCardsRoot", scoreCardsRoot);
            request.setAttribute("scoreCardScore", scoreCardScore);
            request.setAttribute("scoreCardColor", scoreCardColor);
            request.setAttribute("scoreCardChildren", scoreCardChildren);
            
            request.setAttribute("scoreCardChildrenWeight", scoreCardChildrenWeight);
            request.setAttribute("dimensionalCutsMembers", dimensionalCutsMembers);

        } else if (request.getParameter("update") != null && request.getParameter("update").length() > 0) {
            if (request.getParameter("date") != null) {
                Integer tmpDate[] = new Integer[3];
                StringTokenizer dateTokens = new StringTokenizer(request.getParameter("date"), "/");
                for (Integer tmp : tmpDate) {
                    tmp = new Integer(dateTokens.nextToken());
                }
                int lastDayOfMonth;
                switch (tmpDate[1] - 1) {
                    case 1:
                    case 3:
                    case 5:
                    case 7:
                    case 8:
                    case 10:
                    case 12:
                        lastDayOfMonth = 31;
                        break;
                    case 2:
                        if (new GregorianCalendar().isLeapYear(tmpDate[2])) {
                            lastDayOfMonth = 30;
                        } else {
                            lastDayOfMonth = 28;
                        }
                        break;
                    default:
                        lastDayOfMonth = 30;
                        break;
                }
                request.getSession().setAttribute("date", new Date(tmpDate[2], tmpDate[1] - 1, lastDayOfMonth));
            }
            String json = request.getParameter("update");
            LinkedList<Long> ids = new LinkedList<Long>();
            LinkedList<ScoreCard> scoreCardsRoot = new LinkedList<ScoreCard>();
            Map<ScoreCard, String> scoreCardColor = new HashMap<ScoreCard, String>();
            Map<ScoreCard, Double> scoreCardScore = new HashMap<ScoreCard, Double>();
            Map<ScoreCard, Integer> scoreCardChildren = new HashMap<ScoreCard, Integer>();
            json = json.substring(2, json.length() - 2); // quita los corchetes
            StringTokenizer token = new StringTokenizer(json, ",");
            while (token.hasMoreTokens()) {
                ids.push(Long.parseLong(token.nextToken()));
            }
            for (Long id : ids) {
                ScoreCard scoreCard = delegate.findScoreCard(id);
                scoreCardsRoot.add(scoreCard);
                Score score = ScoreCardUtils.calculateScore(delegate, ScoreCardUtils.getSystemComparation(request), scoreCard, ScoreCardUtils.getSystemDate(request));

                /*
                System.out.println("USE AJAX");
                System.out.println("Comparation: " + ScoreCardUtils.getSystemComparation(request));
                System.out.println("Pointer: " + scoreCard.getName());
                System.out.println("Date: " +ScoreCardUtils.getSystemDate(request).toString());*/
                if(scoreCard instanceof Pointer){
                    if(!score.isOutOfDate()) {
                        scoreCardScore.put(scoreCard, score.getScore());
                        Colorimetry colorimetry = delegate.findColorimetry(scoreCard, score.getScore());
                        scoreCardColor.put(scoreCard, colorimetry == null ? "" : colorimetry.getColor());
                    }
                } else {
                    scoreCardScore.put(scoreCard, score.getScore());
                    Colorimetry colorimetry = delegate.findColorimetry(scoreCard, score.getScore());
                    scoreCardColor.put(scoreCard, colorimetry == null ? "" : colorimetry.getColor());
                }
                scoreCardChildren.put(scoreCard, new Integer(delegate.findScoreCard(scoreCard).size()));
            }

            //Update members of all dimensional cuts
            //List of all DimensionalCuts
            List<DimensionalCut> dimensionalCuts = ScoreCardUtils.getDimensionalCuts(request, delegate);

            //Se obtiene los strings de los cuts
            java.util.Map<DimensionalCut, String> dimensionalCutsMembers = ScoreCardUtils.getDimensionalCutsMembersStrings(request, delegate, dimensionalCuts);

            request.setAttribute("scoreCardsRoot", scoreCardsRoot);
            request.setAttribute("scoreCardScore", scoreCardScore);
            request.setAttribute("scoreCardColor", scoreCardColor);
            request.setAttribute("scoreCardChildren", scoreCardChildren);

            request.setAttribute("dimensionalCutsMembers", dimensionalCutsMembers);

        }
        response.setContentType("application/json");
    }
}
